import MysApi from "../../genshin/model/mys/mysApi.js"

export default class BH3MysApi extends MysApi {
  /**
   * 扩展新的 API 接口类型
   * @param type 新的 API 类型标识
   * @param data 接口参数
   * @param cached 是否缓存（继承父类逻辑）
   */
  async getBH3ApiData(type, data = { headers: {} }, cached = false) {
    const bh3map = {
      bh3_cn: () => ({
        url: `https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie`,
        query: `game_biz=bh3_cn`
      }),
      UserGame: () => ({
        url: `${host}binding/api/getUserGameRolesByCookie`,
        query: `game_biz=bh3_cn&region=${this.server}&game_uid=${this.uid}`
      }),
      getFp: () => ({
        url: `${hostPublicData}device-fp/api/getFp`,
        body: {
          app_name: 'bbs_cn',
          bbs_device_id: `${this.uuid}`,
          device_fp: '38d805c20d53d',
          device_id: 'cc57c40f763ae4cc',
          ext_fields: `{"proxyStatus":1,"isRoot":0,"romCapacity":"768","deviceName":"${modelName}","productName":"${productName}","romRemain":"727","hostname":"BuildHost","screenSize":"1096x2434","isTablet":0,"aaid":"${this.uuid}","model":"${modelName}","brand":"${deviceBrand}","hardware":"qcom","deviceType":"${deviceType}","devId":"REL","serialNumber":"unknown","sdCapacity":224845,"buildTime":"1692775759000","buildUser":"BuildUser","simState":1,"ramRemain":"218344","appUpdateTimeDiff":1740498108042,"deviceInfo":"${deviceInfo}","vaid":"${this.uuid}","buildType":"user","sdkVersion":"33","ui_mode":"UI_MODE_TYPE_NORMAL","isMockLocation":0,"cpuType":"arm64-v8a","isAirMode":0,"ringMode":2,"chargeStatus":1,"manufacturer":"${deviceBrand}","emulatorStatus":0,"appMemory":"768","osVersion":"${osVersion}","vendor":"unknown","accelerometer":"-1.588236x6.8404818x6.999604","sdRemain":218214,"buildTags":"release-keys","packageName":"com.mihoyo.hyperion","networkType":"WiFi","oaid":"${oaid}","debugStatus":1,"ramCapacity":"224845","magnetometer":"-47.04375x51.3375x137.96251","display":"${deviceDisplay}","appInstallTimeDiff":1740498108042,"packageVersion":"2.35.0","gyroscope":"-0.22601996x-0.09453133x0.09040799","batteryStatus":88,"hasKeyboard":0,"board":"${board}"}`,
          platform: '2',
          seed_id: `${this.uuid}`,
          seed_time: new Date().getTime() + ''
        }
      }),
      deviceLogin: () => ({
        url: 'https://bbs-api.miyoushe.com/apihub/api/deviceLogin',
        body: {
          app_version: '2.73.1',
          device_id: data.deviceId,
          device_name: `${deviceBrand}${modelName}`,
          os_version: '33',
          platform: 'Android',
          registration_id: this.generateSeed(19)
        }
      }),
      saveDevice: () => ({
        url: 'https://bbs-api.miyoushe.com/apihub/api/saveDevice',
        body: {
          app_version: '2.73.1',
          device_id: data.deviceId,
          device_name: `${deviceBrand}${modelName}`,
          os_version: '33',
          platform: 'Android',
          registration_id: this.generateSeed(19)
        }
      }),
      /** 记忆战场*/
      battleFieldReport: () => ({
        url: `https://act-api-takumi.mihoyo.com/game_record/appv2/honkai3rd/api/battleFieldReport`,
        query: `role_id=${this.uid}&server=${this.server}`,
        method: "get",
      }),
      dailyNote: () => ({
        url: `https://api-takumi-record.mihoyo.com/game_record/appv2/honkai3rd/api/note`,
        query: `role_id=${this.uid}&server=${this.server}`
      }),
      /** 超弦空间*/
      newAbyssReport: () => ({
        url: `https://act-api-takumi.mihoyo.com/game_record/appv2/honkai3rd/api/newAbyssReport`,
        query: `role_id=${this.uid}&server=${this.server}`,
        method: "get",
      }),
      oldAbyssReport: () => ({
        url: `https://act-api-takumi.mihoyo.com/game_record/appv2/honkai3rd/api/oldAbyssReport`,
        query: `role_id=273372943&server=bb01&abyss_type=1`,
        method: "get",
      }),
      /** 主页信息*/
      index: () => ({
        url: `https://act-api-takumi.mihoyo.com/game_record/appv2/honkai3rd/api/index`,
        query: `role_id=${this.uid}&server=${this.server}`,
        method: "get",
      }),
      /** 一周战绩 */
      weeklyReport: () => ({
        url: `https://act-api-takumi.mihoyo.com/game_record/appv2/honkai3rd/api/weeklyReport`,
        query: `role_id=${this.uid}&server=${this.server}`,
        method: "get",
      }),
      /** 往世乐土 */
      godWar: () => ({
        url: `https://act-api-takumi.mihoyo.com/game_record/appv2/honkai3rd/api/godWar`,
        query: `role_id=${this.uid}&server=${this.server}`,
        method: "get",
      }),
      /** 角色信息 */
      characters: () => ({
        url: `https://act-api-takumi.mihoyo.com/game_record/appv2/honkai3rd/api/characters`,
        query: `role_id=${this.uid}&server=${this.server}`,
        method: "get",
      }),
      /** 本月手账 */
      MonthInfo: () => ({
        url: `https://api.mihoyo.com/bh3-weekly_finance/api/index`,
        query: `game_biz=bh3_cn&bind_uid=${this.uid}&bind_region=${this.server}`,
      }),
      /** 上月手账 */
      LastMonthInfo: () => ({
        url: `https://api.mihoyo.com/bh3-weekly_finance/api/getLastMonthInfo`,
        query: `game_biz=bh3_cn&bind_uid=${this.uid}&bind_region=${this.server}`,
      }),
      /**水晶明细 */
      HcoinRecords: () => ({
        url: `https://api.mihoyo.com/bh3-weekly_finance/api/getHcoinRecords`,
        query:`page=1&limit=20&size=20&game_biz=bh3_cn&bind_uid=${this.uid}&bind_region=${this.server}`
      }),
      /**星石明细 */
      StarRecords: () => ({
        url: `https://api.mihoyo.com/bh3-weekly_finance/api/getStarRecords`,
        query: `?page=1&limit=20&size=20&game_biz=bh3_cn&bind_uid=${this.uid}&bind_region=${this.server}`
      })
    }

    if (bh3map[type]) {
      const config = bh3map[type]()
      let { url, query = "", body = "", method } = config
      if (query) url += `?${query}`
      if (body) body = JSON.stringify(body)

      const headers = this.getHeaders(query, body)

      Object.assign(headers, data.headers)
      headers.Cookie = this.cookie

      const cacheKey = this.cacheKey(type, data)
      const cachedData = await redis.get(cacheKey)
      if (cachedData) return JSON.parse(cachedData)

      const param = {
        method: method || "get",
        headers,
        agent: await this.getAgent(),
        timeout: 10000,
      }

      if (body && method !== "get") {
        param.body = body
      }

      logger.mark(`[BH3-Plugin][扩展接口][${type}][${this.uid}]`)
      const response = await fetch(url, param)

      if (!response.ok) {
        logger.error(
          `[BH3-Plugin][扩展接口][${type}][${this.uid}] 请求失败 ${response.status} ${response.statusText}`,
        )
        return false
      }
      const res = await response.json()
      logger.mark(res)
      if (cached) this.cache(res, cacheKey)
      return res
    }

    return super.getData(type, data, cached)
  }
}
